package lib.bone.admin.controller.research;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.access.config.cycle.NepuCycle;
import lib.bone.access.config.cycle.NepuCycleService;
import lib.bone.access.config.cycle.NepuCycleServiceTestImpl;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.access.module.dict.DictServiceCtl;
import lib.bone.access.module.dict.dao.NepuTopicDictDAO;
import lib.bone.access.module.dict.entity.NepuTopicDict;
import lib.bone.access.module.dict.impl.TopicDictServiceImpl;
import lib.bone.access.module.oss.NepuResearchFileService;
import lib.bone.access.module.post.NepuPostService;
import lib.bone.access.module.userpost.NepuUserPostService;
import lib.bone.admin.anno.FormLock;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.admin.controller.system.dto.TopicDTO;
import lib.bone.admin.controller.system.dto.TopicImportDTO;
import lib.bone.admin.controller.system.listener.TopicListener;
import lib.bone.admin.domain.dto.FileUpdateDTO;
import lib.bone.audit.impl.CycleCreatedEventImpl;
import lib.bone.audit.workload.domain.dto.TeachingWorkloadImportDTO;
import lib.bone.audit.workload.listener.TeachingWorkloadListener;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.core.redis.RedisCache;
import lib.bone.common.utils.JsonUtil;
import lib.bone.ext.draft.NepuDraft;
import lib.bone.ext.draft.NepuDraftService;
import lib.bone.flow.constant.FlowWorkStatusConst;
import lib.bone.flow.domain.dto.FlowParam;
import lib.bone.flow.domain.entity.FlowTask;
import lib.bone.flow.domain.entity.FlowWork;
import lib.bone.flow.service.FlowTaskService;
import lib.bone.flow.service.FlowWorkCtl;
import lib.bone.flow.service.FlowWorkService;
import lib.bone.nepudata.domain.dto.topic.*;
import lib.bone.nepudata.domain.entity.NepuTopic;
import lib.bone.nepudata.service.NepuOvertimeProjectService;
import lib.bone.nepudata.service.ResearchServiceCtl;
import lib.bone.nepudata.service.impl.NepuTopicServiceImpl;
import lib.bone.system.domain.entity.SysDept;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.module.iojob.domain.IOJob;
import lib.bone.system.module.iojob.service.IOJobService;
import lib.bone.system.service.SysDeptService;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.text.html.Option;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author  : cg
 * 未完成
 */


@Slf4j
@RestController
@Api(tags = "纵向课题")
@RequestMapping("nepu")
public class NepuTopicController {

    @Value("${file-upload-service.path}")
    private String fileParentPath;

    @Autowired
    NepuDraftService draftService;


    @Autowired
    ResearchServiceCtl researchServiceCtl;

    @Autowired
    DictServiceCtl dictServiceCtl;

    @Autowired
    RedisCache redisCache;

    @Autowired
    NepuTopicServiceImpl nepuTopicService;

    @Autowired
    NepuResearchFileService nepuResearchFileService;

    @Autowired
    FlowWorkCtl flowWorkCtl;

    @Autowired
    NepuCycleService cycleService;

    @Autowired
    NepuWorkloadService workloadService;

    @Autowired
    IOJobService ioJobService;

    @Autowired
    FlowWorkService flowWorkService;


    @Autowired
    SysUserService userService;

    @Autowired
    TopicDictServiceImpl topicDictService;

    @Autowired
    FlowTaskService flowTaskService;

    @Autowired
    CycleCreatedEventImpl cycleCreatedEvent;

    @Autowired
    SysUserService sysUserService;




    /**
     * 表单校验
     * @param dto
     * @return
     */
    public String formValid(NepuTopicAddDTO dto){
        // 表单重复性校验
        String errMsg = "";
//        Optional<NepuTopic> topicOp = nepuTopicService.getByTopicCode(
//                dto.getTopicCode()
//        );
//        if (topicOp.isPresent()) {
//            errMsg = "存在重复记录";
//            return errMsg;
//        }
        Long operator = StpUtil.getLoginIdAsLong();
        Long leaderId = dto.getLeaderId();
        if (!leaderId.equals(operator)){
            errMsg = "您不是负责人，无法申报该项目";
            return errMsg;
        }
        List<Long> userIds = dto.getUserIdList();
        if (userIds.contains(dto.getLeaderId())){
            errMsg = "参与人员中不需添加负责人";
            return errMsg;
        }
        return errMsg;
    }



    @PostMapping("topics/{topicId}/fix")
    @ApiOperation(value = "单个工作量修复")
    public ResponseDTO<Object> fixTopic(@PathVariable("topicId") String topicId){
        Optional<NepuTopic> topicOp = nepuTopicService.getById(topicId);
        if (!topicOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuTopic topic = topicOp.get();
        nepuTopicService.fixWorkload(topic);
        return ResponseDTO.succMsg("更新成功");
    }

    @PostMapping("topics/fix/save")
    @ApiOperation(value = "未新建修复")
    public ResponseDTO<Object> topicFixSave(){
        Optional<NepuCycle> nepuCycleOp = cycleService.getById("2c9046928547939801882221e51e0007");
        if (!nepuCycleOp.isPresent()){
            return ResponseDTO.wrapMsg(ResponseCodeConst.NOT_FOUND,"周期不存在！");
        }
        NepuCycle nepuCycle = nepuCycleOp.get();
        cycleCreatedEvent.process(nepuCycle);
        return ResponseDTO.succMsg("纵向课题工作量修复完成！");
    }

    @PostMapping("topics/fix")
    @ApiOperation(value = "工作量全修复")
    public ResponseDTO<Object> fixTopics(){
       List<NepuTopic> topics = nepuTopicService.getAll();
       topics.forEach(ele->{
           nepuTopicService.fixWorkload(ele);
       });
       return ResponseDTO.succMsg("调用修复任务");
    }


    @PostMapping("topics/storage")
    @FormLock(lockKey = "TOPIC_STORE",needLogin = true)
    @ApiOperation(value = "暂存记录",notes = "")
    public ResponseDTO<Object> setStorage(@RequestBody  NepuTopicAddDTO dto){
        Long userId = StpUtil.getLoginIdAsLong();
        NepuDraft draft = new NepuDraft();
        draft.setFormId(ResearchTypeConst.TOPIC);
        draft.setStatus(1);
        draft.setUserId(userId);
        draft.setFormJsonStr(JsonUtil.obj2String(dto));
        return ResponseDTO.succData(draftService.saveOne(draft));
    }


    @PostMapping("topic/import")
    @ApiOperation(value = "纵向课题导入")
    public ResponseDTO topicImport(MultipartFile file, @RequestParam("cycleId") String cycleId) throws IOException {
        Optional<NepuCycle> cycleOp = cycleService.getById(cycleId);
        // 新建导入任务
        IOJob ioJob = ioJobService.createImportJob();
        if (!cycleOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuCycle nepuCycle = cycleOp.get();
        String parentCycleId = nepuCycle.getParentId();
        EasyExcel.read(file.getInputStream(), TopicImportDTO.class, new TopicListener(userService,ioJobService,nepuTopicService,cycleId,parentCycleId, ioJob.getId(), fileParentPath,draftService,topicDictService,nepuCycle,dictServiceCtl,workloadService)).sheet(0).doRead();
        return ResponseDTO.succMsg("写入成功");
    }

    @GetMapping("topics/storage")
    @ApiOperation(value = "获取最新暂存")
    public ResponseDTO<Object> getStorage(){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<NepuDraft> draftOp = draftService.getLastDraft(userId,ResearchTypeConst.TOPIC);
        if (!draftOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuDraft draft = draftOp.get();
        return ResponseDTO.succData(JsonUtil.string2Obj(draft.getFormJsonStr(),NepuTopicAddDTO.class));
    }

    @GetMapping("topics/storage/all")
    @ApiOperation(value = "获取全部暂存")
    public ResponseDTO<Object> getAllStorage(){
        Long userId = StpUtil.getLoginIdAsLong();
        List<NepuDraft> drafts = draftService.getFormAllDrafts(userId,ResearchTypeConst.TOPIC);
        return ResponseDTO.succData(drafts);
    }


    @GetMapping(value = "topics")
    @ApiOperation(value = "查询全部",notes = "")
    public ResponseDTO<Object> getAll(NepuTopicQueryDTO nepuTopicQueryDTO){
        Sort sort;
        if(nepuTopicQueryDTO.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, nepuTopicQueryDTO.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, nepuTopicQueryDTO.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(nepuTopicQueryDTO.getPageNum() - 1 , nepuTopicQueryDTO.getPageSize(), sort);
        NepuTopic nepuTopic = new NepuTopic();
        BeanUtil.copyProperties(nepuTopicQueryDTO,nepuTopic, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<NepuTopic> example = Example.of(nepuTopic);
        return ResponseDTO.succData(nepuTopicService.getAll(pageable,example));
       // return nepuTopicService.getAll(pageable,example);
    }

    @WebLog(module = "nepu-access")
    @PostMapping(value = "topics")
    @FormLock(lockKey = "TOPIC_FORM",needLogin = true)
    @ApiOperation(value = "新建记录",notes = "")
    public ResponseDTO<Object> saveOne(@RequestBody @Validated NepuTopicAddDTO nepuTopicAddDTO){
//        // PRE 重复性校验 -- 根据课题编码
        //List<NepuTopic> topics = nepuTopicService.getByTopicCodeAsList(nepuTopicAddDTO.getTopicCode());
        // 这个修改后是取第一个
        Optional<NepuTopic> topicOp = nepuTopicService.getByTopicCode(nepuTopicAddDTO.getTopicCode());
        if (topicOp.isPresent()){
            NepuTopic topic = topicOp.get();
            Optional<FlowWork> flowWorkOp = flowWorkService.getByServiceId(topic.getId());
            if (!flowWorkOp.isPresent()){
                return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"对应流程实例不存在！");
            }else {
                FlowWork flowWork = flowWorkOp.get();
                if (flowWork.getFlowWorkStatus().equals(FlowWorkStatusConst.CLOSED)){
                    //跳过
                }else {
                    return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"课题编码重复，本周期的工作量将自动结转，无需申报！");
                }
            }
        }
        //
//        if (topics.size()!=0){
//            for (NepuTopic topic : topics) {
//                Optional<FlowWork> flowWorkOp = flowWorkService.getByServiceId(topic.getId());
//                if (!flowWorkOp.isPresent()){
//                    return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"对应流程实例不存在！");
//                }else {
//                    FlowWork flowWork = flowWorkOp.get();
//                    if (flowWork.getFlowWorkStatus().equals(FlowWorkStatusConst.CLOSED)){
//                        //跳过
//                    }else {
//                        return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"课题编码重复，本周期的工作量将自动结转，无需申报！");
//                    }
//                }
//            }
//        }
//        // 1. 获取当前登录用户ID -- 自动拦截未登录用户
//        String operator = StpUtil.getLoginIdAsString();
//        String leaderId = nepuTopicAddDTO.getLeaderId().toString();
//        if (!leaderId.equals(operator)){
//            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"您不是负责人，无法申报该项目");
//        }
//        if (nepuTopicAddDTO.getUserIdList().contains(nepuTopicAddDTO.getLeaderId())){
//            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"参与人员不需加入负责人");
//        }
        // 2. 获取当前时间所在周期 -- 自动拦截不在时间段内的提交
//        NepuCycle cycle = cycleService.getNowCycle();
        NepuCycle cycle = cycleService.getNowResearchCycle();
        System.out.println("cycle:"+cycle);
        // 1. 获取操作人员ID
        String operator = StpUtil.getLoginIdAsString();
        // 2. 表单校验
        String errMsg = formValid(nepuTopicAddDTO);
        if (!Validator.isEmpty(errMsg)){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,errMsg);
        }
        //  立项时间早于结束时间
        if (!nepuTopicAddDTO.getStartDate().before(cycle.getEndDate())&&nepuTopicAddDTO.getIsOverTime().equals(0)){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"立项时间必须早于本周期结束时间");
        }
        // 结束时间必须晚于本周期开始时间
        if (!nepuTopicAddDTO.getEndDate().after(cycle.getStartDate())&&nepuTopicAddDTO.getIsOverTime().equals(0)){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"课题结束时间必须在本周期开始时间之后");
        }
        // 3. 获取词典信息
        Optional<Object> topicdictOp = dictServiceCtl.getById(nepuTopicAddDTO.getTopicDictId(),ResearchTypeConst.TOPIC);
        if (!topicdictOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuTopicDict dict = (NepuTopicDict) topicdictOp.get();
        // 4. 写入记录 并赋值最大工作量
        NepuTopic saveEntity = new NepuTopic();
//        saveEntity.setCycleId(cycleService.getNowCycleId());
        saveEntity.setCycleId(cycleService.getNowResearchCycleId());
        BeanUtil.copyProperties(nepuTopicAddDTO,saveEntity,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        BeanUtil.copyProperties(nepuTopicAddDTO,saveEntity,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
//        BigDecimal receiveFunds = new BigDecimal(nepuTopicAddDTO.getReceivedFunds());
//        BigDecimal topicFunds = new BigDecimal(nepuTopicAddDTO.getTopicFunds());
//        saveEntity.setReceivedFunds(receiveFunds.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
//        saveEntity.setTopicFunds(topicFunds.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        saveEntity.setReceivedFunds(nepuTopicAddDTO.getReceivedFunds());
        saveEntity.setTopicFunds(nepuTopicAddDTO.getTopicFunds());
        //saveEntity.setWorkload(dict.getWorkloadMax());
        // 纵向课题工作量赋予 -- 从开始到结束可以获取到的全部工作量
        Date startDate = nepuTopicAddDTO.getStartDate();
        Date endDate = nepuTopicAddDTO.getEndDate();
        // 2022-5-30 bug fix
        long betweenMonth = DateUtil.betweenMonth(startDate,endDate,false) + 1;
        double totalWorkload = dict.getWorkloadMax() * betweenMonth * 1.0 / 12;
        saveEntity.setWorkload(totalWorkload);

        NepuTopic topic = (NepuTopic) researchServiceCtl.saveOne(saveEntity);
        // 5. 写入绑定文件信息 -- 修改为异步任务
        List<String> fileIds = nepuTopicAddDTO.getFileIds();
        nepuResearchFileService.batchBindFile(ResearchTypeConst.TOPIC,topic.getId(),fileIds);
        // 6. 构建流程参数
        FlowParam flowParam = new FlowParam(ResearchTypeConst.TOPIC,topic.getId(),topic.getTopicName(),operator,null);
//        flowParam.setServiceType(ResearchTypeConst.TOPIC);
//        flowParam.setServiceId(topic.getId());
//        flowParam.setServiceName(topic.getTopicName());
//        flowParam.setOperator(operator);
        // 7. 启动流程实例 -- 修改为异步任务
        switch (nepuTopicAddDTO.getDeptName()){
            case "科研处": {
                flowWorkCtl.startProcess("topic-check-01", operator, flowParam);
                break;
            }
            case "教务处":{
                flowWorkCtl.startProcess("topic-check-02", operator, flowParam);
                break;
            }
            case "研究生部":{
                flowWorkCtl.startProcess("topic-check-03", operator, flowParam);
                break;
            }
            case "高等教育研究中心":{
                flowWorkCtl.startProcess("topic-check-04", operator, flowParam);
                break;
            }
            case "学科建设处":{
                flowWorkCtl.startProcess("topic-check-05", operator, flowParam);
                break;
            }
            case "招生就业处":{
                flowWorkCtl.startProcess("topic-check-06", operator, flowParam);
                break;
            }
        }
        return ResponseDTO.succData(topic);
    }

//    @PutMapping("topic/{topicId}/delay")
    @PostMapping("topics/{topicId}/delay")
    @ApiOperation(value = "课题延期")
    public ResponseDTO<Object> delayTopic(@PathVariable("topicId") String topicId, @RequestBody @Validated TopicDelayDTO delayDTO){
        Optional<Object> topicOp = researchServiceCtl.getById(topicId,ResearchTypeConst.TOPIC);
        if (!topicOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuTopic topic = (NepuTopic) topicOp.get();
        if (topic.getEndDate().after(delayDTO.getEndDate())){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"延期日期早于当前结项日期");
        }
        // 延期日期
        topic.setEndDate(delayDTO.getEndDate());
        // 关联文件写入
        List<String> fileIds = delayDTO.getFileIds();
        nepuResearchFileService.batchBindFile(ResearchTypeConst.TOPIC,topic.getId(),fileIds);
        return ResponseDTO.succData(nepuTopicService.updateOne(topic));
    }

    @PostMapping("topics/{topicId}/advance")
    @ApiOperation(value = "课题提前结项")
    public ResponseDTO<Object> advanceTopic(@PathVariable("topicId") String topicId, @RequestBody @Validated TopicAdvanceDTO advanceDTO){
        Optional<Object> topicOp = researchServiceCtl.getById(topicId,ResearchTypeConst.TOPIC);
        if (!topicOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuTopic topic = (NepuTopic) topicOp.get();
        if (topic.getEndDate().before(advanceDTO.getEndDate())){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"提前结项日期应早于当前结项日期");
        }
        // 延期日期
        topic.setEndDate(advanceDTO.getEndDate());
        // 关联文件写入
        List<String> fileIds = advanceDTO.getFileIds();
        nepuResearchFileService.batchBindFile(ResearchTypeConst.TOPIC,topic.getId(),fileIds);
        return ResponseDTO.succData(nepuTopicService.updateOne(topic));
    }

//    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping(value = "topics")
    @ApiOperation(value = "更新单条记录",notes = "")
    public ResponseDTO<Object> updateOne(@RequestBody @Validated TopicUpdateDTO topicUpdateDTO){
        Optional<Object> topicOp = researchServiceCtl.getById(topicUpdateDTO.getId(),ResearchTypeConst.TOPIC);
        if (!topicOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        List<FlowTask> list = flowTaskService.getByServiceId(topicUpdateDTO.getId());
        for (FlowTask flowTask : list) {
            FlowParam flowParam = new FlowParam();
            BeanUtil.copyProperties(topicUpdateDTO,flowParam,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            flowParam.setServiceName(topicUpdateDTO.getTopicName());
            String str = JsonUtil.obj2String(flowParam);
            flowTask.setFlowParam(str);
            flowTask.setServiceName(topicUpdateDTO.getTopicName());
            flowTaskService.saveOne(flowTask);
        }
        NepuTopic topic = (NepuTopic) topicOp.get();
        BeanUtil.copyProperties(topicUpdateDTO,topic,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return ResponseDTO.succData(researchServiceCtl.updateOne(topic,ResearchTypeConst.TOPIC));
    }

    @GetMapping(value = "topics/{id}")
    @ApiOperation(value = "查询单条记录",notes = "")
    public ResponseDTO<Object> getOne(@PathVariable("id") String id){
        Optional<Object> entityOp = researchServiceCtl.getById(id,ResearchTypeConst.TOPIC);
        return entityOp.map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND));
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.DELETE)
    @DeleteMapping(value = "topics/{id}")
    @ApiOperation(value = "删除单条记录",notes = "")
    public ResponseDTO<Object> deleteOne(@PathVariable("id") String id){
        return researchServiceCtl.deleteById(id,ResearchTypeConst.TOPIC);
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping("topics/files")
    @ApiOperation(value = "更新附件信息",notes = "")
    public ResponseDTO<Object> updateFiles(@RequestBody @Validated FileUpdateDTO dto){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<Object> topicOp = researchServiceCtl.getById(dto.getMapperId(),ResearchTypeConst.TOPIC);
        if (!topicOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuTopic topic = (NepuTopic) topicOp.get();
        if (!userId.equals(topic.getLeaderId())){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"非负责人无法修改");
        }
        // 清理之前的附件信息
        nepuResearchFileService.deleteEntityLink(topic.getId());
        // 写入新的附件信息
        List<String> fileIds = dto.getFileIds();
        nepuResearchFileService.batchBindFile(ResearchTypeConst.TOPIC,topic.getId(),fileIds);
        // 返回操作信息
        return ResponseDTO.succMsg("更新成功");
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping("topics/{id}/workload")
    @ApiOperation(value = "修改记录工作量")
    public ResponseDTO<Object> updateWorkload(@PathVariable("id") String id,@RequestParam("workload") Double workload){
        Optional<Object> entityOp = researchServiceCtl.getById(id,ResearchTypeConst.TOPIC);
        if (!entityOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到对应课题记录");
        }
        NepuTopic topic = (NepuTopic) entityOp.get();
        String dictId = topic.getTopicDictId();
        Optional<Object> dictOp = dictServiceCtl.getById(dictId,ResearchTypeConst.TOPIC);
        if (!dictOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到课题关联词典记录");
        }
        Date startDate=topic.getStartDate();
        Date endDate=topic.getEndDate();
        long betweenDay = DateUtil.between(startDate,endDate, DateUnit.DAY);
        NepuTopicDict dict = (NepuTopicDict) dictOp.get();
        int monthCount = (int) (betweenDay/30 + 1);
        Integer monthworkloadMax = dict.getWorkloadMax()/12+(dict.getWorkloadMax()%12!=0?1:0);
        Integer workloadMax = monthworkloadMax*monthCount;
        Integer monthworkloadMin = dict.getWorkloadMin()/12+(dict.getWorkloadMin()%12!=0?1:0);
        Integer workloadMin = monthworkloadMin*monthCount;
        if (workload > workloadMax || workload < workloadMin){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"工作量范围错误");
        }
        topic.setWorkload(workload);
        // 写入记录
        return ResponseDTO.succData(researchServiceCtl.updateOne(topic,ResearchTypeConst.TOPIC));
    }





//    @GetMapping(value = {"/getAll"})
//    @ApiOperation(value = "查询全部",notes = "")
//    public ResponseDTO getAll(){
//        return nepuTopicService.getAll();
//    }
//
//    @GetMapping(value = {"/delOneById/{id}"})
//    @ApiOperation(value = "删除单个数据",notes = "传入id，删除数据")
//    public ResponseDTO deleteOneById(@PathVariable("id") String id){
//        return nepuTopicService.deleteById(id);
//    }
//
//    @PostMapping(value = {"nepuResearchWorkload"})
//    @ApiOperation(value = "新建一条数据",notes = "")
//    public ResponseDTO savePaperDict(@RequestBody NepuTopic nepuTopic){
//        return nepuTopicService.save(nepuTopic);
//    }
//
//    @PutMapping(value = {"/longdict"})
//    @ApiOperation(value = "更新一条数据",notes = "")
//    public ResponseDTO updateTopicDict(@RequestBody NepuTopic nepuTopic){
//        return nepuTopicService.save(nepuTopic);
//    }
//
//    @GetMapping(value = {"/apply/{id}"})
//    @ApiOperation(value = "申请",notes = "")
//    public ResponseDTO apply(@PathVariable("id") String id){
//        return nepuTopicService.apply(id);
//    }
}
